package com.mxchip.livestar.ui.call


import android.app.Dialog
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.*
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import com.mxchip.livestar.R
import com.mxchip.livestar.base.*
import com.mxchip.livestar.base.AppConstant
import com.mxchip.livestar.base.hideSystemUI
import com.mxchip.livestar.repository.RoomClientRepository
import com.mxchip.livestar.ui.call.InviteDialogFragmentDirections.actionInviteDialogFragmentToAddMemberFragment
import com.videohigh.graham.SampleSDK
import kotlinx.android.synthetic.main.fragment_invite_dialog.*


class InviteDialogFragment : DialogFragment(), TextWatcher, TextView.OnEditorActionListener {

    private val roomViewModel by activityViewModels<RoomViewModel>()
    private val contactViewModel by viewModels<ContactViewModel>()

    private val adapter: InviteAdapter by lazy {
        InviteAdapter()
    }

    // private val sampleSDK = SampleSDK.getInstance()

    override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}

    override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
        contactViewModel.searchWord(if (count > 0) s.toString() else null)
    }

    override fun afterTextChanged(s: Editable) {}

    override fun onEditorAction(v: TextView?, actionId: Int, event: KeyEvent?): Boolean {
        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            val keyword = v?.text?.toString()
            // 当按了搜索之后关闭软键盘
            hideKeyboard()
            /*(Objects.requireNonNull(context)!!.getSystemService(
                    Context.INPUT_METHOD_SERVICE) as InputMethodManager).hideSoftInputFromWindow(
                    Objects.requireNonNull(Objects.requireNonNull(activity)!!.currentFocus).windowToken,
                    InputMethodManager.HIDE_NOT_ALWAYS)*/
            //搜索
            return keyword.isNullOrEmpty()
        }
        return false
    }

    override fun onDestroyView() {
        super.onDestroyView()
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_invite_dialog, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        contact_search_key.addTextChangedListener(this)
        contact_search_key.setOnEditorActionListener(this)

        recycler_view.showEmpty()
        recycler_view.setLayoutManager(LinearLayoutManager(context))
        recycler_view.adapter = adapter

        contactViewModel.contactFilterList.observe(viewLifecycleOwner, Observer { list  ->
            adapter.setData(list)
            adapter.notifyDataSetChanged()
        })

        roomViewModel.termIdsAll.observe(viewLifecycleOwner, Observer {terms ->
            adapter.setBanTermIds(terms.map { it.termId })
            adapter.notifyDataSetChanged()
        })

        button_add.setOnClickListener {
            Log.e(TAG, "onAddClick")
            findNavController().navigate(actionInviteDialogFragmentToAddMemberFragment())
        }

        button_invitation.setOnClickListener {
            Log.e(TAG, "onInvitationClick")

            val selected = adapter.getSelectedContacts()
            // val termIds = emptySet<String>() // roomViewModel.getTermIdsAll()?: emptySet()

            if (selected.isNullOrEmpty()) {
                toast("请选择邀请成员")
                return@setOnClickListener
            }

            /*if (selected.size + termIds.size > AppConstant.MAX_CHOOSE_NUMBER) {
                toast("目前只支持${AppConstant.MAX_CHOOSE_NUMBER+1}方通话")
                return@setOnClickListener
            }*/

            val ids = selected.map { it.contactNumber!! }.toTypedArray()

            // Log.e(TAG, "termIds: ${ids.contentToString()}")

            RoomClientRepository.invite(ids, { session ->
                Log.i(TAG, "invite resp $session")
            }, {code, message ->
                Log.e(TAG, "invite $code $message")
            })

            findNavController().popBackStack()
        }

        button_cancel.setOnClickListener {
            Log.e(TAG, "onCancelClick")
            findNavController().popBackStack()
        }
    }

    override fun onStart() {
        context?.apply {
            val width = resources.displayMetrics.widthPixels * 0.4
            val height = resources.displayMetrics.heightPixels * 0.8
            dialog?.window?.setLayout(width.toInt(), height.toInt())
        }

        dialog?.window?.setFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE)

        super.onStart()

        dialog?.window?.clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE)
    }

    override fun onResume() {
        super.onResume()
        dialog?.window?.hideSystemUI()
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val dialog = super.onCreateDialog(savedInstanceState)

        dialog.window?.decorView?.setOnSystemUiVisibilityChangeListener { visibility ->
            if (visibility and View.SYSTEM_UI_FLAG_FULLSCREEN == 0) {
                // adjustments to your UI, such as showing the action bar or
                // other navigational controls.
                dialog.window?.hideSystemUI()
            } else {
                // adjustments to your UI, such as hiding the action bar or
                // other navigational controls.
            }
        }
        return dialog
    }

    companion object {
        private const val TAG = "InviteDialogFragment"
    }

}
